const HtmlWebpackPlugin = require("html-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const ReactRefreshTypeScript = require("react-refresh-typescript");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ESlintPlugin = require("eslint-webpack-plugin");
const path = require("path");
const webpack = require("webpack");
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

const isDevelopment = process.env.NODE_ENV !== "production";

module.exports = {
  output: {
    filename: "index.js",
    path: path.resolve(process.cwd(), "lib"),
    clean: true,
    library: "libraryName",
    libraryTarget: "umd",
    umdNamedDefine: true,
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".json"],
    alias: {
      "~": path.resolve("src"),
    },
  },

  module: {
    rules: [
      {
        oneOf: [
          {
            test: /\.[jt]sx?$/,
            exclude: /node_modules/,
            use: [
              {
                loader: "ts-loader",
                options: {
                  getCustomTransformers: () => ({
                    before: [isDevelopment && ReactRefreshTypeScript()].filter(
                      Boolean
                    ),
                  }),
                  transpileOnly: isDevelopment,
                },
              },
            ],
          },
          {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: "babel-loader",
            options: {
              cacheDirectory: true, // 开启babel缓存
              cacheCompression: false, // 关闭缓存压缩
            },
          },
          {
            test: /\.less$/,
            exclude: /node_modules/,
            use: [
              MiniCssExtractPlugin.loader,
              "css-loader",
              "postcss-loader",
              "less-loader",
            ],
          },
          {
            test: /\.css$/,
            exclude: /node_modules/,
            use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader"],
          },
          {
            test: /\.md$/,
            exclude: /node_modules/,
            type: "asset",
          },
          {
            test: /\.(png|jpe?g|gif|webp)$/,
            type: "assets",
          },
        ],
      },
    ],
  },
  plugins: [
    new ESlintPlugin({
      context: path.resolve(process.cwd(), "src"),
    }),
    new MiniCssExtractPlugin({ filename: "index.css" }),
    isDevelopment && new ReactRefreshWebpackPlugin(),
    isDevelopment &&
      new HtmlWebpackPlugin({
        template: "./demo/index.html",
      }),
    isDevelopment && new webpack.HotModuleReplacementPlugin(), // 热更新
    !isDevelopment && new BundleAnalyzerPlugin({ analyzerMode: "static" }),
  ].filter(Boolean),
};
